package com.zhao.fishingguideserver.utils;

import com.zhao.fishingguideserver.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 鱼类图片批量处理工具
 */
@Component
@Slf4j
public class FishImageBatchProcessor {
    
    @Autowired
    private OssService ossService;
    
    /**
     * 批量上传鱼类图片
     * @param imageFolder 本地图片文件夹路径
     * @param fishNames 鱼类名称列表（与图片文件名对应）
     * @return 处理结果
     */
    public Map<String, Object> batchUploadFishImages(String imageFolder, List<String> fishNames) {
        Map<String, Object> result = new HashMap<>();
        Map<String, String> successUploads = new HashMap<>();
        Map<String, String> failedUploads = new HashMap<>();
        
        try {
            Path folderPath = Paths.get(imageFolder);
            if (!Files.exists(folderPath)) {
                throw new IOException("图片文件夹不存在: " + imageFolder);
            }
            
            File folder = folderPath.toFile();
            File[] imageFiles = folder.listFiles((dir, name) -> {
                String lowerName = name.toLowerCase();
                return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || 
                       lowerName.endsWith(".png") || lowerName.endsWith(".gif");
            });
            
            if (imageFiles == null || imageFiles.length == 0) {
                throw new IOException("文件夹中没有找到图片文件");
            }
            
            log.info("找到 {} 个图片文件", imageFiles.length);
            
            for (int i = 0; i < imageFiles.length && i < fishNames.size(); i++) {
                File imageFile = imageFiles[i];
                String fishName = fishNames.get(i);
                
                try {
                    // 将File转换为MultipartFile
                    MultipartFile multipartFile = new FileMultipartFile(imageFile);
                    
                    // 清理鱼类名称
                    String cleanFishName = fishName.replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9]", "_");
                    
                    // 上传到OSS
                    String fileUrl = ossService.uploadFileWithName(multipartFile, "fish-images/", cleanFishName);
                    
                    successUploads.put(fishName, fileUrl);
                    log.info("成功上传: {} -> {}", fishName, fileUrl);
                    
                } catch (Exception e) {
                    failedUploads.put(fishName, e.getMessage());
                    log.error("上传失败: {} - {}", fishName, e.getMessage());
                }
            }
            
            result.put("successUploads", successUploads);
            result.put("failedUploads", failedUploads);
            result.put("totalCount", imageFiles.length);
            result.put("successCount", successUploads.size());
            result.put("failedCount", failedUploads.size());
            
        } catch (Exception e) {
            log.error("批量处理失败", e);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 生成鱼类图片URL的SQL更新语句
     * @param fishImageMap 鱼类名称和图片URL的映射
     * @return SQL更新语句列表
     */
    public List<String> generateUpdateSql(Map<String, String> fishImageMap) {
        List<String> sqlList = new ArrayList<>();
        
        for (Map.Entry<String, String> entry : fishImageMap.entrySet()) {
            String fishName = entry.getKey();
            String imageUrl = entry.getValue();
            
            String sql = String.format(
                "UPDATE freshwater_fish_china_1979 SET fish_img_url = '%s' WHERE species_name = '%s';",
                imageUrl, fishName
            );
            sqlList.add(sql);
        }
        
        return sqlList;
    }
    
    /**
     * 自定义MultipartFile实现
     */
    private static class FileMultipartFile implements MultipartFile {
        private final File file;
        private final String contentType;
        
        public FileMultipartFile(File file) {
            this.file = file;
            this.contentType = "image/jpeg"; // 默认类型
        }
        
        @Override
        public String getName() {
            return file.getName();
        }
        
        @Override
        public String getOriginalFilename() {
            return file.getName();
        }
        
        @Override
        public String getContentType() {
            return contentType;
        }
        
        @Override
        public boolean isEmpty() {
            return file.length() == 0;
        }
        
        @Override
        public long getSize() {
            return file.length();
        }
        
        @Override
        public byte[] getBytes() throws IOException {
            return Files.readAllBytes(file.toPath());
        }
        
        @Override
        public java.io.InputStream getInputStream() throws IOException {
            return Files.newInputStream(file.toPath());
        }
        
        @Override
        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
            Files.copy(file.toPath(), dest.toPath());
        }
    }
}
